<template>
  <div>
    <!-- 头部 -->
    <myDivider name="修改工单"></myDivider>
    <el-page-header @back="$router.back(-1)">
    </el-page-header>

    <!-- 表单 -->
    <el-form :rules="rules" ref="ruleFormRef" class="fromStyle" :model="formData" label-width="150px">
      <div style="display: flex;">
        <el-form-item label="报事日期：">
          <div style="width: 222px;">
            {{ formData.acceptTime }}
          </div>
        </el-form-item>
        <el-form-item label="事件编号：">
          <div style="width: 222px;">
            {{ formData.eventsNumber }}
          </div>
        </el-form-item>
      </div>
      <div style="display: flex;">
        <el-form-item label="报事类别：">
          <el-select disabled style="width: 222px;" v-model="formData.eventsCategory" placeholder="请选择报事类别">
            <el-option label="报修" value="1"></el-option>
            <el-option label="咨询" value="2"></el-option>
            <el-option label="建议" value="3"></el-option>
            <el-option label="表扬" value="4"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="服务类别：" v-if="formData.eventsCategory == 1">
          <el-select disabled style="width: 222px;" v-model="formData.category" placeholder="请选择服务服务类表">
            <el-option label="电路" value="1"></el-option>
            <el-option label="电器" value="2"></el-option>
            <el-option label="主体结构" value="3"></el-option>
            <el-option label="给排水" value="4"></el-option>
            <el-option label="综合类" value="5"></el-option>
          </el-select>
        </el-form-item>
      </div>

      <el-form-item label="报事区域：">
        <el-input style="width: 594px" placeholder="报事区域" disabled v-model="regionText"></el-input>
      </el-form-item>

      <!-- 客户信息 -->
      <div style="display: flex;">
        <el-form-item label="客户信息：">
          <el-input disabled style="width: 222px;" v-model="formData.customerName" placeholder=""></el-input>
        </el-form-item>
        <el-form-item label="联系方式：">
          <el-input disabled style="width: 222px;" v-model="formData.phone" placeholder=""></el-input>
        </el-form-item>
      </div>

      <el-form-item label="报事方式：">
        <el-select disabled style="width: 222px;" v-model="formData.orderWay" placeholder="请选择报事方式">
          <el-option label="来访" value="1"></el-option>
          <el-option label="呼叫中心" value="2"></el-option>
          <el-option label="内部人员反馈" value="3"></el-option>
          <el-option label="客户端" value="4"></el-option>
          <el-option label="其它渠道" value="5"></el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="预约时间：">
        <div style="width: 594px;display: flex;justify-content: space-between;">
          <el-date-picker style="width: 222px;" ref="Time" value-format="yyyy-MM-dd" v-model="formData.reservationDay"
            type="date" placeholder="选择日期" :picker-options="pickerOptions" @change="Timechange">
          </el-date-picker>
          <el-select :disabled="!formData.reservationDay" style="width: 360px;" v-model="formData.reservationInterval"
            placeholder="请选择时间">
            <el-option v-for="item, i in TimeSelect" :key="i" :label="item.val" :value="item.val"
              :disabled="item.disabled">
            </el-option>
          </el-select>
        </div>
      </el-form-item>

      <el-form-item label="报事内容：" prop="eventsDescription">
        <el-input style="width: 594px;" type="textarea" show-word-limit :rows="3" maxlength="200" placeholder="请输入内容"
          v-model="formData.eventsDescription">
        </el-input>
      </el-form-item>

      <el-form-item label="报事图片：">
        <MyUploadImgNotDetele v-if="myNewUploadShow" :id="uploadId" @getImgList="getImgList"
          @deleteImgList="deleteImgList" :EchoImgList="EchoImgList" uploadUrl="/business/order/uploadImg">
        </MyUploadImgNotDetele>
      </el-form-item>

      <div style="display: flex;">
        <el-form-item label="内部工单号：">
          <el-input style="width: 220px;" maxlength="30" placeholder="请输入内部工单号" v-model="formData.orderNumber">
          </el-input>
        </el-form-item>
        <el-form-item label="单据号：" label-width="80px">
          <div style="width: 100px;">
            {{ formData.workOrderNumber }}
          </div>
        </el-form-item>
        <el-form-item label="工单状态：" label-width="100px">
          <div style="width: 100px;">
            {{ formData.workOrderState }}
          </div>
        </el-form-item>
      </div>
      <el-form-item label="工单级别：">
        <el-select style="width: 222px;" v-model="formData.urgency" placeholder="请选择工单级别">
          <el-option label="一般" value="1"></el-option>
          <el-option label="紧急" value="2"></el-option>
          <el-option label="特急" value="3"></el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="任务进度：" v-if="myOrderStatusList.length > 0">
        <div class="rwjdList">
          <div class="el" v-for="item, i in myOrderStatusList" :key="i">
            <div class="top">
              <div>
                <div class="cir"></div>
              </div>
              <div><span style="font-weight: bold;">{{ item.d1 }}</span>（{{ item.d2 }}）
              </div>
              <div>{{ item.d3 }}</div>
              <div>
                <span v-if="item.d4">
                  {{ item.d4 }}
                </span>
              </div>
              <div>时间：{{ item.d5 }}</div>
            </div>

          </div>
        </div>
      </el-form-item>
    </el-form>
    <div class="btn">
      <el-button style="width: 100px;" @click="goBack">取消</el-button>
      <el-button style="width: 100px;" type="primary" @click="submit">保存</el-button>
    </div>


  </div>
</template>

<script>
import MyUploadImgNotDetele from '@/components/upload/MyUploadImgNotDetele.vue'
export default {

  components: {
    MyUploadImgNotDetele
  },
  data() {
    return {
      pickerOptions: {
        disabledDate(time) {
          let a = time.getTime()
          let b = Date.now() - 8.64e7
          let is = a < b
          return is;
        },
      },

      regionText: '',
      formData: {},
      logOnUser: {},
      rules: {
        eventsDescription: [
          { required: true, message: '请输入报事内容', trigger: 'blur' }
        ],
      },
      TimeSelect: [
        { val: '08:00:00~09:00:00', disabled: false },
        { val: '09:00:00~10:00:00', disabled: false },
        { val: '10:00:00~11:00:00', disabled: false },
        { val: '11:00:00~12:00:00', disabled: false },
        { val: '14:00:00~15:00:00', disabled: false },
        { val: '15:00:00~16:00:00', disabled: false },
        { val: '16:00:00~17:00:00', disabled: false },
        { val: '17:00:00~18:00:00', disabled: false },
      ],
      //  回显的图片路径
      EchoImgList: [],
      myNewUploadShow: false,
      uploadId: 0,
      deleteImg: [],
      myOrderStatusList: [],
    }
  },

  async activated() {
    this.formData = {}
    this.logOnUser = JSON.parse(sessionStorage.getItem('logOnUser'))
    let res = await this.$api.events.DetailWork(this.$route.query.id)

    if (res.code != 200) {
      this.$message.error(res.message)
      return
    }
    let data = res.data
    // 处理进度
    this.myOrderStatusList = []
    res.data.orderStatusList.forEach(el => {
      let d1 = ''
      let d2 = ''
      let d3 = ''
      let d4 = ''
      switch (el.status) {
        case '1':
          d1 = el.oper == '1' ? '办理' : '退单'
          d2 = '工单登记'
          d3 = `经办人：${el.userName}`
          d4 = ''
          break
        case '2':
          d1 = el.oper == '1' ? '派单' : '退单'
          d2 = '任务派工'
          d3 = `经办人：${el.userName}`
          d4 = `服务人员：${el.workerName}`
          break
        case '3':
          d1 = el.oper == '1' ? '结单' : '退单'
          d2 = '任务回单'
          d3 = `结单人：${el.workerName}`
          d4 = ''
          break
        case '4':
          d1 = el.oper == '1' ? '归档' : '退单'
          d2 = '工单归档'
          d3 = `归档人：${el.workerName}`
          d4 = `处理结果：${res.data.result ? res.data.result : '--'}`
          break
      }
      this.myOrderStatusList.push({
        d1, d2, d3, d4, d5: el.createTime
      })
    })
    // 处理图片
    this.deleteImg = []
    this.uploadId = res.data.id
    if (res.data.imgs == null) {
      this.EchoImgList = []
      this.$set(this.formData, 'imgs', [])
    } else {
      this.EchoImgList = res.data.imgs
      this.$set(this.formData, 'imgs', res.data.imgs)
    }
    this.myNewUploadShow = false
    setTimeout(() => {
      this.myNewUploadShow = true
    }, 500);
    console.log(data, '工单详情');
    // 表单相关
    if (data.isPublic == 1) { //公共区域
      this.regionText = `${data.residentialName}/公共区域`
      this.formData.region = [data.residentialId, 0]
    } else { //私人区域
      this.regionText = `${data.residentialName}/${data.buildingName}/${data.unitCode}/${data.floors}/${data.roomName}`
      this.formData.region = [data.residentialId, data.buildingId, data.unitCode, data.floors, data.roomId]
    }
    this.formData.acceptTime = data.acceptTime
    this.formData.eventsNumber = data.eventsNumber
    this.$set(this.formData, 'id', data.id)
    this.$set(this.formData, 'eventId', data.eventId)

    this.$set(this.formData, 'eventId', data.eventId)
    this.$set(this.formData, 'isPublic', data.isPublic)
    this.$set(this.formData, 'buildingId', data.buildingId)
    this.$set(this.formData, 'roomId', data.roomId)
    this.$set(this.formData, 'depts', data.depts)
    this.$set(this.formData, 'workerId', data.workerId)
    this.$set(this.formData, 'status', data.status)

    this.$set(this.formData, 'eventsCategory', res.data.eventsCategory)
    this.$set(this.formData, 'category', res.data.category)
    this.$set(this.formData, 'serviceCategory', data.serviceCategory)
    this.$set(this.formData, 'customerId', data.customerId)
    this.$set(this.formData, 'customerName', data.customerName)
    this.$set(this.formData, 'phone', data.phone)
    this.$set(this.formData, 'orderWay', data.orderWay)
    this.$set(this.formData, 'reservationDay', data.reservationDay)
    this.$set(this.formData, 'reservationInterval', data.reservationInterval)
    this.$set(this.formData, 'eventsDescription', data.eventsDescription)
    this.$set(this.formData, 'orderNumber', data.orderNumber)
    this.$set(this.formData, 'urgency', data.urgency)


    this.$nextTick(() => {
      this.$refs['ruleFormRef'].clearValidate()
    })
  },
  methods: {
 

    submit() {
      this.$refs['ruleFormRef'].validate((valid) => {
        if (valid) {

          this.$confirm('是否修改？', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(async () => {
            this.deleteImg.forEach(async (el) => {
              let res = await this.$api.ImgFile.delete(defaultUrl + '/business/order/deleteImg', {
                "picName": el
              })
            })
            if (this.formData.region.length == 2) { //说明是公共区域
              //如果是公共区域
              this.formData.isPublic = 1
              this.formData.buildingId = 0
              this.formData.roomId = 0
            } else if (this.formData.region.length == 5) { //说明是私人区域
              this.formData.isPublic = 0
              this.formData.buildingId = this.formData.region[1]
              this.formData.roomId = this.formData.region[4]
            }
            // 把roomId获取到
            this.formData.residentialId = this.formData.region[0]


            console.log(this.formData, '提交的东西');
            let res = await this.$api.axios.post('/business/order/updateOrder', this.formData)
            if (res) {
              this.$message({
                type: 'success',
                message: '修改成功!'
              });
              this.$router.go(-1)
            }

          }).catch(() => {

          });
        } else {
          return false;
        }
      });
    },
    goBack() {
      this.$router.go(-1)
    },

    getSelectTime(e) {
      const today = new Date();
      const inputDate = new Date(e);
      today.setHours(0, 0, 0, 0);
      inputDate.setHours(0, 0, 0, 0);
      // 如果是今天，那么把今天之前的时间都设为不可选
      if (today.toISOString().slice(0, 10) === inputDate.toISOString().slice(0, 10)) {
        let time = new Date()
        this.TimeSelect.forEach(el => {
          el.disabled = time.getHours() >= el.val.slice(0, 2)
        })
      } else {
        this.TimeSelect.forEach(el => {
          el.disabled = false
        })
      }
    },
    // 当前要上传的图片列表
    getImgList(val) {
      console.log('当前选择的图片', val)
      this.formData.imgs = val
    },
    deleteImgList(val) {
      this.deleteImg.push(val)
    },
    // 点击日期后，时间筛选
    Timechange(e) {
      this.$set(this.formData, 'reservationInterval', null)
      this.getSelectTime(e)
    },

    // 递归
    dgfun(res) {
      let arr = []
      res.forEach(el => {
        // 如果有孩子们，继续遍历
        if (el.children != null) {
          el.children = this.dgfun(el.children)
        }
        arr.push({
          value: el.id,
          label: el.name,
          children: el.children,
        })
      })
      return arr
    },
  },

}
</script>

<style lang="less" scoped>
.rwjdList {
  .el {
    margin-bottom: 25px;


    .top {
      display: flex;
      align-items: center;

      >div {
        &:nth-child(1) {
          .cir {
            width: 8px;
            height: 8px;
            border-radius: 100px;
            background-color: #0043ce;
            box-shadow: 0 0 6px 3px #b1cdfa;
          }

          flex: 1;
        }

        &:nth-child(2) {
          flex: 6;
        }

        &:nth-child(3) {
          flex: 9;
        }

        &:nth-child(4) {
          flex: 9;
        }

        &:nth-child(5) {
          flex: 12;
        }
      }
    }

    .main {

      img {
        width: 100px;
        height: 100px;

      }

    }

  }
}

.Timestyle {
  position: relative;

  /deep/ .is-disabled {
    .el-input__inner {
      background-color: white;
      color: black;
    }
  }

  >span {
    position: absolute;
    right: 160px;
    top: 50%;
    transform: translateY(-50%);
  }
}

.fromStyle {
  margin: 50px 0 0 50px;
  width: 1000px;
}

// 添加取消按钮
.btn {
  background-color: white;
  position: fixed;
  bottom: 0;
  right: 0;
  width: 100%;
  height: 80px;
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow: 0 0 4px 1px #e1e1e1;

}
</style>